package com.panfeng.xcloud.common.core.utils;

import org.apache.commons.lang3.RandomStringUtils;
import org.jolokia.util.Base64Util;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;

/**
 * @author xiaobo
 */
public class DES3Util {

    // 加解密统一使用的编码方式
    private final static String ENCODING = "utf-8";

    /**
     * 3DES加密
     * @param plainText 加密文本
     * @param secretKey 秘钥
     * @param iv 向量
     * @return
     * @throws Exception
     */
    private static String encode(String plainText,String secretKey,String iv) throws Exception {
        Key desKey;
        DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("desede");
        desKey = keyFactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
        IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, desKey, ips);
        byte[] encryptData = cipher.doFinal(plainText.getBytes(ENCODING));
        return Base64Util.encode(encryptData);
    }

    /**
     * 两次加密 需要doubleDecode进行解密
     * @param plainText
     * @param secretKey
     * @param iv
     * @return
     */
    public static String doubleEncode(String plainText,String secretKey,String iv){
        try {
            //第一次加密
            String encode = encode(plainText, secretKey, iv);
            //用向量的MD5结果的8位计算出新的向量
            String iv2 = getEightMD5(iv,secretKey);
            secretKey = secretKey.substring(8)+iv2;
            String result = encode(encode, secretKey, iv2);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 进行两次解密
     * @param encryptText
     * @param secretKey
     * @param iv
     * @return
     */
    public static String doubleDecode(String encryptText,String secretKey,String iv)  {

        //用向量的MD5结果的8位计算出新的向量
        try {
            String iv2 = getEightMD5(iv,secretKey);
            String secretKey2 = secretKey.substring(8)+iv2;
            String decode = decode(encryptText, secretKey2, iv2);
            String result = decode(decode, secretKey, iv);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 获取随机向量
     * @return
     */
    public static String getRandomIv(){
        return RandomStringUtils.randomAlphanumeric(8);
    }

    /**
     * 根据原向量获取二次向量
     *
     * @param vi 原向量
     * @param secretKey 秘钥
     * @return
     */
    private static String getEightMD5(String vi,String secretKey){
        String md5Str = MD5.MD5Encode(vi+".xuedaowang."+secretKey);
        Integer offset = 0;

        if(md5Str != null && !"".equals(md5Str)) {
            for (int i = 0; i < md5Str.length(); i++) {
                if (md5Str.charAt(i) >= 48 && md5Str.charAt(i) <= 57) {
                    offset = Integer.parseInt(""+md5Str.charAt(i));
                    break;
                }
            }
            return md5Str.substring(offset,offset+8);
        }
        return null;
    }



    /**
     * 3DES解密
     *
     * @param encryptText 加密文本
     * @param secretKey 秘钥
     *      * @param iv 向量
     * @return
     * @throws Exception
     */
    private static String decode(String encryptText,String secretKey,String iv) throws Exception {
        Key deskey;
        DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("desede");
        deskey = keyFactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
        IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
        byte[] decryptData = cipher.doFinal(Base64Util.decode(encryptText));
        return new String(decryptData, ENCODING);
    }


    public static void main(String[] args) throws Exception {
        for (int i =0 ;i <100;i++){

            String org = RandomStringUtils.randomAlphanumeric(32);
            String iv = getRandomIv();

            long l = System.currentTimeMillis();
            String jiamihou = doubleEncode(org,"q3zQvAXvPLVIjxY0NsrLn_.V#*xEV4gz",iv);
            String jiemihou = doubleDecode(jiamihou,"q3zQvAXvPLVIjxY0NsrLn_.V#*xEV4gz",iv);
            System.out.println("原始值：" + org);
            System.out.println("加密：" + jiamihou+"   "+jiamihou.length());
            System.out.println("解密：" + jiemihou);
            long l2 = System.currentTimeMillis();
            System.out.println("第"+i+"次结束耗时 =============="+(l2-l)+"ms");

        }
    }
}
